package cn.crex1.xiaomi.common.filter;

import java.io.IOException;
import javax.servlet.DispatcherType;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@WebFilter(dispatcherTypes = { DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.INCLUDE,
		DispatcherType.ERROR }, urlPatterns = {
				"/*" }, initParams = { @WebInitParam(name = "character", value = "UTF-8") })
public class CharacterFilter implements Filter {

	private static Logger logger = LoggerFactory.getLogger(CharacterFilter.class);

	private String characterKey = "character";
	
	private String characterValue = "";

	public CharacterFilter() {

	}

	public void destroy() {

	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
		
		req.setCharacterEncoding(characterValue);
		resp.setCharacterEncoding(characterValue);
		
		resp.setContentType("text/html;charset=utf-8");
		
		logger.debug("CharacterFilter:set Character"+characterValue);
		
		chain.doFilter(req, resp);
	}

	public void init(FilterConfig fConfig) throws ServletException {
		characterValue=fConfig.getInitParameter(characterKey);
		logger.debug("CharacterFilter start filter");
	}

}
